clear;
close all
clear persistent
clear global
clear mex
close all;
drawnow;
%#ok<*NOPTS>
%% make sure the eye tracker is running before anything else
enableCallbacks = 'PsychEyelinkDispatchCallback'; %special secret ninja hidden code
home;
if Eyelink('Initialize', enableCallbacks) ~= 0
    InitializeDummy=questdlg_offscreen('Eyelink is not properly connected. Initialize in Dummy mode?', ...
        'Eyelink is not connected!', ...
        'Yes','Quit','Yes');
    if strcmp(InitializeDummy,'Yes')
        if Eyelink('InitializeDummy', enableCallbacks) ~=0
            fprintf('InitializeDummy failed too\n')
            return;
        end
    else
        fprintf('cancled by user\n')
        return;
    end
end
%%
fprintf('\nSTART\n')
clear
c=define_colors(256);
c.BACKGROUND=c.BLACK;
c.GO=c.RED;
c.NG=c.RED;
c.TTEXT=c.WHITE;
edf_name='edf_name';

screenRect=get(0,'ScreenSize');
screenpixW=screenRect(3);
screenpixH=screenRect(4);
c_x=screenpixW/2;
c_y=screenpixH/2;
set(0,'DefaultFigurePosition',[screenpixW*1.25 screenpixH/4   screenpixW/2   screenpixH/2 ])
wherearewe=questdlg_offscreen('Which Computer are you on?', ...
    'Where are you?', ...
    'Prometheus','Sham','Magnet','Sham');
switch wherearewe
    % computer specific information
    case 'Prometheus'
        home_folder='C:\Users\BCoe\DATA\MRI\dorris\inspection';
        distance2screen=66;% cm
        screenwidth=37.7; %-ish  cm
        sheightinches=screenwidth*3/4;
        Screen('Preference', 'SkipSyncTests', 1);
    case 'Sham'
        home_folder='C:\_user\_bcoe\data\dorris\inspection';
        armorbore=questdlg_offscreen('Usingthe ARM mount or in the sham?', ...
            'Where are you?', ...
            'ARM','Bore','ARM');
        switch armorbore
            case 'ARM'
                distance2screen=24;% inches
                screenwidth=340*0.0393700787; % inches
                sheightinches=270*0.0393700787; % inches
                %sheightinches/screenwidth
            case 'Bore'
                distance2screen=23;% inches ???
                screenwidth=17; % inches ???
                sheightinches=screenwidth*3/4;
                disp('dont know these yet');
                return
            otherwise
                disp('cancled by user')
                return
        end
    case 'Magnet'
        home_folder='E:\_User\_bcoe\Data\Dorris\inspection';
        distance2screen=57;% inches
        screenwidth=18; % inches
        sheightinches=screenwidth*3/4;
    otherwise
        disp('cancled by user')
        return
        
end
clear ButtonName screenRect
drawnow;
dphs = atan2(screenwidth/2,distance2screen)*180/pi;%degrees per half screen
ppd = screenpixW/2/dphs; %pixels/degree
uimenufcn(0,'WindowCommandWindow');

%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%   ASSIGN PARAMETERS   %%
%%%%%%%%%%%%%%%%%%%%%%%%%%%
% First, try to load table of parameter names and set values
try % this should speed things along if your running a few studies on the same subject
    cd(home_folder)
    load('temp')
    for par = 1:size(Parameters,1)% assign each parameter in the table to its value
        eval([Parameters{par,1} '=''' Parameters{par,2} ''';']); % for string entries
    end
    sub_inits% % check if it exists
    sub_code% check if it exists
    if ~strcmp(kyou,datestr(now,'yyyy-mm-dd'))% check if it exists & ...
        error('not todays date');% if today's date doesn't match the date in the temp file force 'try' to fail
    end
    file_nb=sprintf('%02d',str2num(file_nb)+1)%#ok<*ST2NM> % check if it exists & increment
        TR% check if it exists
    t1eq_scans% check if it exists
    fix_dur% check if it exists
    tgt_dur% check if it exists
    tgt_ecc% check if it exists
    %blk_dur
    out_dur
    R_Fix % inter trial fixation duration
    IB_Fix
    NOR % number of repetitions
    game
    gor
catch parametertry %%#ok<CTCH> % else start from defaults (in string format)
    parametertry.message
    parametertry.stack
    disp(' -> loading default settings');
    beep;
    sub_inits='XXX';
    sub_code='00000';
    kyou=datestr(now,'yyyy-mm-dd');
    file_nb='00';
    TR='2000';
    t1eq_scans='2';  %T1 saturation scans
    fix_dur='800';
    tgt_dur='800';
    tgt_ecc='6.5';
    %blk_dur='0';
    out_dur='800';
    R_Fix  ='800';
    IB_Fix ='6*TR';
    NOR='20';
    game='1,2';
    gor='1';
    cd(home_folder)
save('temp','Parameters','kyou');    % saves temp data (still in string format)

end
clc
Parameters={...% variable  value           'discription'                                                  string or number?
    'sub_inits',	sub_inits,		'Subjects 3 Initials (ABC)',                                        's';...
    'sub_code',	    sub_code,		'Subjects 5 Digit MRI code (00000)',                                's';...
    'file_nb',		file_nb,		'File # (or run #, always 2 digits):',                              's';...
    'TR',	        TR,          	'TR (in millisecs)',                                                'n';...
    't1eq_scans',	t1eq_scans, 	'# of T1 Equilibrium scans (in TR)',                                'n';...
    'fix_dur',	    fix_dur,        'Duration of Fixation (in ms or "TR*n")',                           'n';...
    'tgt_dur',	    tgt_dur,        'Duration of Target   (in ms or "TR*n")',                           'n';...
    'tgt_ecc',	    tgt_ecc,        'Eccentricity of Target (from FIX in deg''s)',                      'n';...
    %'blk_dur',	    blk_dur,        'Duration of Gap (in ms or "TR*n")',                                'n';...
    'out_dur',	    out_dur,        'Duration of Feedback (in ms or "TR*n")',                           'n';...
    'R_Fix',        R_Fix,          'Duration of rest fixation(in ms or "TR*n")',                       'n';...
    'IB_Fix',       IB_Fix,         'Duration of InterBlock Fixation(in ms or "TR*n")',                 'n';...
    'NOR',          NOR,            'Number of Repetitions ',                                           'n';...
    'game',         game,           'GAME: 1)matching pennies 2)inspection game ',                      'n';...
    'gor',          gor,            'risky on left(1) or right(0)',                                     'n';...
    };
%now set the numeric data to numbers
for par= find(char(Parameters{:,4})=='n')' % for numeric entries
    eval([Parameters{par,1} '=[' Parameters{par,2} '];']);
    eval([Parameters{par,1} '=' Parameters{par,1} '(:);' ]); % force to vertical
end
clear par


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% define event codes (for communication)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% i=127; % max (open) code for IScan
% e.trialend=char(i); i=i-1;% end of trial code for IScan;
% e.stimoff=char(i); i=i-1;
% e.stimon=char(i); i=i-1;
% e.tgtoff=char(i); i=i-1;
% e.tgton=char(i); i=i-1;
% e.fixoff=char(i); i=i-1;
% e.fixon=char(i); i=i-1;


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% define states (video presentation)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
i=1;
%S.WAIT  =i;    t_state{i}='Waiting';       i=i+1;
S.T1EQ   =i;    t_state{i}='T1 Equ';        i=i+1;
S.IB_FIX =i;    t_state{i}='InterBlock Fix';i=i+1;
S.FIX    =i;    t_state{i}='Start Fix';     i=i+1;
S.TGT    =i;    t_state{i}='Target';        i=i+1;
%S.BLANK  =i;    t_state{i}='Blank';         i=i+1;
S.RESPOND=i;    t_state{i}='Responded';     i=i+1;
S.OUTCOME=i;    t_state{i}='Outcome';       i=i+1;
S.R_FIX  =i;    t_state{i}='Rest Fix';      i=i+1;
S.ENDTASK=i;    t_state{i}='End Task';      i=i+1;

state_time(1:i-1)=0;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% define state timing & update parameters
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
file_name=[Parameters{1,2} '.' kyou '_' Parameters{3,2} ];

update=2;
while update
    if update==1 % skip interface the first time to do calculations
        clc;
        fprintf('%s \n',['Duration of Paragigm: ' num2str(max(state_end_time)) 'ms or ' num2str(floor(max(state_end_time)/60000)) ':' num2str(rem((max(state_end_time)/60000)*60,60)) 'min.'])
        fprintf('%s \n',['Total # of Volumes: ' num2str((max(state_end_time))/TR)  ])
        fprintf('%s \n',['TR=' num2str(TR) 'ms, TR''s per subblock: ' num2str((mean(state_end_time(state_event==S.R_FIX)-state_start_time(state_event==S.FIX))*max_trials)/TR) ])
        fprintf('%s \n',['(' num2str((max(state_end_time))/TR) '*TR)=' num2str(eval(['(' num2str((max(state_end_time))/TR) '*TR)']))]);
        
        %         fprintf('%s \n','# State:    Onset:  Dur:  TR''s: ')
        %         for i=1 :min(find(state_event==S.IBFIX))%length(state_end_time)
        %             spacea='';spacea(1:8-length(t_state{state_event(i)}))=' ';
        %             spaceb='';spaceb(1:6-length(num2str(state_start_time(i))))=' ';
        %             spacec='';spacec(1:7-length(num2str(state_duration(i))))=' ';
        %             spaced='';spaced(1:6-length(num2str(state_duration(i)/TR) ))=' ';
        %             fprintf('%s \n',[num2str(state_event(i)) ': '  t_state{state_event(i)} spacea spaceb num2str(state_start_time(i)) spacec num2str(state_duration(i)) spaced num2str(state_duration(i)/TR) ])
        %         end
        cd(home_folder)
        load('temp') % gets the string versions back
        [ParamInputs update] = inputdlg_offscreen(Parameters(:,3), ['Enter Parameters - ' file_name] , 1, Parameters(:,2));
        if isempty(ParamInputs);
            disp('Task Canceled');
            return
        end
        kyou=datestr(now,'yyyy-mm-dd');% force to todays date
        [Parameters{:,2}] = deal(ParamInputs{:});
        clear ParamInputs
        save('temp','Parameters','kyou');    % saves temp data (still in string format)
        %now set the numeric data to numbers
        for par= find(char(Parameters{:,4})=='n')' % for numeric entries
            eval([Parameters{par,1} '=[' Parameters{par,2} '];']);
            eval([Parameters{par,1} '=' Parameters{par,1} '(:);' ]); % force to vertical
        end
        % save data file
        folder=[Parameters{1,2} '.' kyou];
        if ~exist(folder,'dir')
            eval(['mkdir ' folder]);
        end
        %cd(folder);
        file_name=[Parameters{1,2} '.' kyou '_' Parameters{3,2} ];
        edf_name=[num2str(dayofyear()) Parameters{1,2} Parameters{3,2}];% 8 char limit
        
        if exist([folder filesep file_name '.edf'],'file')
            yesno=questdlg_offscreen('File Exits! Overwrite it?','Be Careful!','Yes','No','No');
            if yesno(1)=='N'
                disp(['File Exists: ' file_name])
                update=1;
                file_nb=str2num(file_nb)+1;% increment
                if file_nb<10
                    file_nb=['0' num2str(file_nb)];
                else
                    file_nb=num2str(file_nb);
                end
                Parameters{3,2}=file_nb;
            end
            clear yesno;
        end
    end % if update==1
    if update>1, update=1;end
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    % start do time stuff  (to be put into a subfunction after debugging is over?)
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    % trial randomization
    max_trials=NOR*2;
    %     if game(sub) == 3
    %         correct_tgt=[];
    %     else
    green_on_right=[];
    green_on_righta=[zeros(1,max_trials/2) ones(1,max_trials/2)];
    %     end %switch game
    
    state_event=[S.T1EQ; S.IB_FIX];
    state_duration=[t1eq_scans*TR; IB_Fix];
    %     state_event(1)=S.T1EQ;
    %     state_event(2)=S.IB_FIX;
    %     state_duration(1)=t1eq_scans*TR;
    %     state_duration(2)=IB_Fix;
    
    for j = 1:length(game)
        green_on_right=[green_on_right, green_on_righta(randperm(max_trials))]; %#ok<AGROW>
        for i = 1:max_trials
            state_event(end+1)=S.FIX; %#ok<SAGROW>
            state_duration(end+1)=fix_dur;%#ok<SAGROW>
            
            state_event(end+1)=S.TGT;%#ok<SAGROW>
            state_duration(end+1)=tgt_dur;%#ok<SAGROW>
            
            %state_event(end+1)=S.BLANK;
            %state_duration(end+1)=blk_dur;
            
            state_event(end+1)=S.OUTCOME;%#ok<SAGROW>
            state_duration(end+1)=out_dur;%#ok<SAGROW>
            
            state_event(end+1)=S.R_FIX;%#ok<SAGROW>
            state_duration(end+1)=R_Fix;   %#ok<SAGROW>
        end
        state_event(end+1)=S.IB_FIX;%#ok<SAGROW>
        state_duration(end+1)=IB_Fix;     %#ok<SAGROW>
    end
    green_on_right(1:end)=gor; % no color
    state_event(end+1)=S.ENDTASK;%#ok<SAGROW>
    state_duration(end+1)=0;%#ok<SAGROW>
    
    state_duration=state_duration(:);
    state_event=state_event(:);
    state_end_time=cumsum(state_duration);
    state_start_time=[0; state_end_time(1:end-1) ];
    response=(green_on_right*0)-1;
    %         [state_event state_duration state_end_time] ;
    cd(home_folder)
    save('temp','Parameters','kyou');    % saves temp data (still in string format)
    file_name=[Parameters{1,2} '.' kyou '_' Parameters{3,2} ];  
end
drawnow;
uimenufcn(0,'WindowCommandWindow');
cd(folder);

game=[game; length(game)+1]; %for final block
rule_text={'Matching Game';'Inspection Game';'thank you'};

%state_end_time=state_end_time/1000;
% strcat(num2str(state_start_time) , '. ' , num2str(state_end_time),'. ',num2str(state_end_time-state_start_time),'. ',char(t_state(state_event)') )

stim_size=.15;% radius of stim
s_circle=[-1 -1	1 1]*ppd*stim_size;      						      % stimulus circle
fix_b=floor([c_x c_y c_x c_y]+([-1 -1	1 1]*ppd*(stim_size/3.5))); % fixation middle
fix_a=floor([c_x c_y c_x c_y]+([-1 -1	1 1]*ppd*stim_size));	      % fixation circle
% [ t_XY(:,1) t_XY(:,2)]=polar2cart(t_ang_ecc(:,1),t_ang_ecc(:,2),1);
% [ s_XY(:,1) s_XY(:,2)]=polar2cart(s_ang_ecc(:,1),s_ang_ecc(:,2),1);
tgt_XY=round([-tgt_ecc 0; tgt_ecc 0; ]*ppd);
for i=1:length(tgt_XY)
    tgt_rect(i,:)=floor([tgt_XY(i,:) tgt_XY(i,:)]+s_circle+[c_x c_y c_x c_y]); %#ok<SAGROW> % for use with mac's LeToRiBo rect shite
end
clear fix_XY tgt_XY stm_XY

%% inspection game info:
alpha=.2  % .1 to .9
lambda=.1 % set to .1
bonus=.1
pshirk=0.5;% likelyhood employee will shirk (assume no knowldge at first)
pshirkadj=0.5; %adjusted likelyhood employee will shirk (assume no knowldge at first)
pinspect=0.5;% likelyhood corp will inspect (assume no knowldge at first)
pinspectadj=0.5; %adjusted likelyhood corp will inspect (assume no knowldge at first)
corpcash=0;%money values
empcash=0;%money values
prevwork=1;%variable to check if work/shirk is repeated (think of the interview as work)
previnspect=1;%variable to check if inspect/ignore is repeated (think of the interview as inspect)

repwindow=20; %how far back to check for local repetition
rep_cnt_emp=uint8(zeros(1,repwindow));
rep_act_emp=0.5;% actual repetition rate for employee
rep_exp_emp=0.5;% corporation's expected repetition rate for employee eq(8)

rep_cnt_corp=uint8(zeros(1,repwindow));
rep_act_corp=0.5;% actual repetition rate for corporation
rep_exp_corp=0.5;% employee's expected repetition rate for corporation eq(8)

prod_gain= .3; % production gain. everything else must be smaller
wage     = .1; % wage earned
effort   =.05; % cost or effort of labor
coi      =.05; % cost of inspection

% prod_gain= .45; % production gain. everything else must be smaller
% wage     = .150; % wage earned
% effort   =.075; % cost or effort of labor
% coi      =.075; % cost of inspection

corpgain(1,1)=prod_gain-wage-coi;
corpgain(1,2)=prod_gain-wage;
corpgain(2,1)=-coi;
corpgain(2,2)=-wage;
% corpgain=corpgain+1;
empgain(1,1)=wage-effort;
empgain(1,2)=wage-effort;
empgain(2,1)=0;
empgain(2,2)=wage;
result(2,2)=0;
prob_inspect=0.5;   %random first inspection
prob_work=.5;       %random first choice
work=[]; %1= work 0= shirk, -1 =noresponse
%% matching pennies game info:
WLD=zeros(1,length(response))+2; % 1=win, -1=lose, 0=draw, 2=noresponse
prob=zeros(1,length(response));
runningtotal=0;
Hinfo=[];
Cinfo=[];
CompStrat='random';
R_bias=0;
correct_tgt=[];

index=1;
trial=0;
state=state_event(index);
event=state;                % start these buffers
r_time=0;
r_TR=0;
r_state=0;
INT_5=single(zeros((max(state_end_time))/TR,1));
subblock=0;
%% Screen
Screen('Preference','SkipSyncTests',1);
Screen ('Preference','VisualDebugLevel',3);
Screen('Preference','SuppressAllWarnings',1);
ListenChar(0);%turn off character listening and reset the buffer which holds the captured characters.
ListenChar(2);%enable listening, additionally any output of keypresses to Matlab windows is suppressed.
[w, wRect]=Screen('OpenWindow', 1, 0,[],32,2);
Screen(w,'BlendFunction',GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
pause(.01);
Screen('fillrect',w,c.BACKGROUND);
screen('flip',w);

Screen('TextStyle',w,1);% 0=plain, 1=bold, 2=italics, 3=1&2,  4=underlined, 5=4&1,6=4&2, 7=4&3. rem(?,8)
Screen('TextFont',w,'Tahoma');
Screen('TextSize',w,40);
ttext='Hit the space bar to continue';
DrawFormattedText(w,ttext,'center',c_y-100,c.TTEXT);
screen('flip',w);
fprintf('Hit the space bar to continue\n')
keyCode(32)=0;
while ~keyCode(32)% SPACE on pcwin
    [keyIsDown,secs,keyCode] = KbCheck; % Warning: mxSetLogical is deprecated and will not be supported in the future. Please refer to the Release Notes for information on updating your code
    if keyIsDown
        if keyCode(27) % esc key
            ttext='Task Aborted';
            DrawFormattedText(w,ttext,'center','center',c.ORANGE);
            screen('flip',w);
            fprintf('%s\n',ttext);
            pause(1);
            Screen('Closeall');
            ListenChar(0);
            return
        else
            FlushEvents;
        end
    end
end
screen('flip',w);

%% Eyelink
% done up front
% if Eyelink('Initialize', enableCallbacks) ~= 0
%     clc
%     disp(' ');
%     status = Eyelink('InitializeDummy');
%     if Eyelink('InitializeDummy', enableCallbacks) ~=0
%         % Failed as well :-(
%         Screen('closeall');
%         ListenChar(0);
%         return;
%     end
% end

%el = EyelinkInitDefaults_bcoe(w); %el=elglobal; %make it local and usable
el = EyelinkInitDefaults(w);%el=elglobal; %make it local and usable
%their default is the inverse of this:
el.backgroundcolour = c.BLACK(1);% bcoe
el.foregroundcolour = c.WHITE(1);% bcoe
el.msgfontcolour    = c.M_GREY(1);% bcoe
el.imgtitlecolour   = c.M_GREY(1);% bcoe
el.calibrationtargetcolour=el.foregroundcolour;
el.eyeimgsize=screenpixW/20+10;
%el.msgfont='Tahoma';
el.msgfontsize=12;
%el.imgtitlefont='Tahoma';
el.imgtitlefontsize=12;
EyelinkUpdateDefaults(el); % need to update it on the host

% make sure that we get gaze data from the Eyelink
Eyelink('Command','calibration_type = HV5');
Eyelink('Command', 'link_sample_data = LEFT,RIGHT,GAZE,AREA');
%Eyelink('command', 'link_sample_data  = LEFT,RIGHT,GAZE,PUPIL,AREA,BUTTON,INPUT');
Eyelink('command', 'link_event_filter = LEFT,RIGHT,SACCADE,BLINK,MESSAGE,BUTTON');
Eyelink('command', 'file_event_filter = LEFT,RIGHT,SACCADE,MESSAGE,BUTTON,INPUT');
openfile = Eyelink('openfile',[edf_name,'.edf']);
if openfile~=0
    disp(['Cannot create EDF file: ' edf_name]);
    ttext='Task Aborted';
    DrawFormattedText(w,ttext,'center','center',c.ORANGE);
    screen('flip',w);
    fprintf('%s\n',ttext);
    Eyelink('setofflinemode');
    Eyelink('shutdown');
    pause(1);
    Screen('Closeall');
    ListenChar(0);
    return;
end
%clear openfile
Eyelink('command', 'add_file_preamble_text', 'Recorded by BCOE');
%el;
fprintf(' entered EyelinkDoTrackerSetup\n')
EyelinkDoTrackerSetup(el);
fprintf('  exited EyelinkDoTrackerSetup\n')
FlushEvents;
pause(.5)
FlushEvents;
Screen('fillrect',w,c.BACKGROUND);
screen('flip',w);
%% wait for magnet to start
ttext='waiting for magnet to start';
DrawFormattedText(w,ttext,'center','center',c.TTEXT);
screen('flip',w);
fprintf('%s\n',ttext);

eyelink('command','clear_screen %d',0);
x(1:12)=c_x;
y(1:12)=c_y;
t(1:12)=GetSecs;t=t+(1:length(t));% gets rid of x/0 error
SetMouse(c_x,c_y);
keyIsDown=0;
buttons=0; % prevent from skipping mouse button loop
while buttons(1)==0
    warning off MATLAB:DeprecatedLogicalAPI;
    [keyIsDown,secs,keyCode] = KbCheck; % Warning: mxSetLogical is deprecated and will not be supported in the future. Please refer to the Release Notes for information on updating your code
    warning on MATLAB:DeprecatedLogicalAPI;
    keyCode=find(keyCode, 1 );
    if keyCode==27% ESC on pcwin
        ttext='Task Aborted';
        DrawFormattedText(w,ttext,'center','center',c.ORANGE);
        screen('flip',w);
        fprintf('%s\n',ttext);
        Eyelink('closefile');
        Eyelink('setofflinemode');
        Eyelink('shutdown');
        pause(1);
        Screen('Closeall');
        ListenChar(0);
        return
    end
    if keyCode==48+5% '5%' on pcwin the new mri trigger
        buttons=1;
    end
    %     temp=simpleserial('bytesready'); % make sure to
    %     if temp > sizeodata*2;
    %         data= simpleserial('read',floor(temp/sizeodata)*sizeodata,'int16');
    %     end
end
Eyelink('StartRecording'); % messages must be after startrecording
fprintf('start recording\n')
%% finally start actual task

Eyelink('message','RETRACE_INTERVAL: 16.667')
Eyelink('message',sprintf('disttoscreen %f sheightinches %f swidthinches %f PPD %f screenpixW %f screenpixH%f',distance2screen,sheightinches,screenwidth,ppd,screenpixW,screenpixH));
%fprintf('disttoscreen %f sheightinches %f swidthinches %f PPD %f ',distance2screen,sheightinches,screenwidth,ppd);
time = Eyelink('TrackerTime')

Screen('flip',w)
fprintf('started\n')
abs_start_time=getsecs;
%simpleserial('write', char(state)); % for IScan
time=getsecs-abs_start_time;% start these buffers
%try


screen('flip',w);
pause(1)

%% stoprecording
Eyelink('stoprecording');
Eyelink('closefile');
ListenChar(0);
fprintf('stop recording\n')
% fade to grey
Screen('TextSize',w,58);
temp=(c.M_GREY-c.BACKGROUND)./80;
for i = 1:80 % fade to ?_GREY algorythm
    Screen('fillrect',w,round(c.BACKGROUND+(temp*i)));
    DrawFormattedText(w,'thank you!','center',c_y-60,c.BLUE);
    DrawFormattedText(w,'please rest.','center',c_y+60,c.BLUE);
    Screen('flip',w);
end
pause(1);
Screen('closeall');
%%

%consolidate and save data at end
A=[];
A.file_name=file_name;
A.where=wherearewe;
A.parameters=Parameters;
%A.eye_used=eye_used;
A.colors=c;
A.states=S;
A.t_state=t_state;
A.state_duration=state_duration;
A.state_end_time=state_end_time;
A.state_time=state_time;
%A.INT_5=INT_5;
A.leftorright=response;
% matching game things
%A.winlose=WLD;
%A.correct_tgt=correct_tgt;
%A.green_on_right=green_on_right;
%A.prob=prob;
% inspection game things
%A.inspect=inspect;
%A.work=work;
save([file_name '.mat'],'A')

pause(1);
ReceiveFilestatus = Eyelink('ReceiveFile',[edf_name '.edf'],[file_name '.edf']);%, ['dest_is_path']
fprintf('Transferred filesize: %3.0fKB\n', ReceiveFilestatus/2^10);

Eyelink('setofflinemode');
Eyelink('shutdown');
fprintf('END\n')
if ReceiveFilestatus>0
    E=EL1k_step01([pwd filesep [file_name '.edf']]);
    FillOval=E.messages(findincell(E.messages,'FillOval'));
    clf;
    hold on
    for tr=1:length(FillOval)
        fred=textscan(FillOval{tr},'%*s %d %d %d','Delimiter',' ()','MultipleDelimsAsOne',1);
        x=single(fred{1}-(E.res.pix_wide/2))/E.res.ppd;
        y=single(fred{2}-(E.res.pix_wide/2))/E.res.ppd;
        d=single(fred{3})*2/E.res.ppd*100;
        s=plot(x,y,'.','markersize',d,'MarkerFaceColor','auto');
        %E.eye.sacloc{tr}(1):E.eye.sacloc{tr}(2)
        plot(E.eye.x{tr}(E.eye.sacloc{tr}(1):E.eye.sacloc{tr}(2)),E.eye.y{tr}(E.eye.sacloc{tr}(1):E.eye.sacloc{tr}(2)),'.g')
    end
    axis ij
end